<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE 示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 20px;
        }

        h1 {
            color: #333;
            text-align: center;
        }

        #message-container {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-top: 20px;
        }

        #message-container p {
            margin: 5px 0;
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        #message-container p:last-child {
            border-bottom: none;
        }

        #error-message {
            color: red;
            text-align: center;
            margin-top: 20px;
        }

        #connection-closed {
            color: #777;
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <h1>实时时间显示</h1>
    <div id="message-container"></div>
    <div id="error-message"></div>
    <div id="connection-closed"></div>

    <script>
        const eventSource = new EventSource('http://localhost:3000/sse');
        const messageContainer = document.getElementById('message-container');
        const errorMessage = document.getElementById('error-message');
        const connectionClosed = document.getElementById('connection-closed');

        eventSource.onmessage = function (event) {
            const newMessage = document.createElement('p');
            newMessage.textContent = event.data;
            messageContainer.appendChild(newMessage);
        };

        eventSource.onerror = function (error) {
            errorMessage.textContent = '连接出错，请检查服务器状态。';
            eventSource.close();
        };

        eventSource.onclose = function () {
            connectionClosed.textContent = '连接已关闭。';
        };
    </script>
</body>

</html>